<template>
  <div class="box">
    <div>
      <el-form ref="form" :model="form" label-width="80px">
        <el-card>
          <el-row :gutter="20">
            <el-col :span="14">
              <el-form-item label="标题" prop="name">
                <el-input v-model="form.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="内容">
                <div
                  style="
                    border: 1px solid #dcdfe6;
                    border-radius: 4px;
                    z-index: 999;
                  "
                >
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editor"
                    :defaultConfig="toolbarConfig"
                  />
                  <Editor
                    class="editor-box"
                    :defaultConfig="editorConfig"
                    :defaultContent="defaultContent"
                    v-model="html"
                    @onChange="onChange"
                    @onCreated="onCreated"
                  />
                </div>
              </el-form-item>
            </el-col>
            <!--            <el-col :span="18">-->
            <!--              <el-form-item label="附件" v-model="form.fileList">-->
            <!--                <el-upload-->
            <!--                  :action="uploadApi"-->
            <!--                  :data="fileData"-->
            <!--                  :headers="headers"-->
            <!--                  :file-list="showFileList"-->
            <!--                  :on-success="handleUpload"-->
            <!--                  :on-remove="handleRemove"-->
            <!--                  multiple-->
            <!--                >-->
            <!--                  <el-button size="small" type="primary">上传附件</el-button>-->
            <!--                </el-upload>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
          </el-row>
        </el-card>
      </el-form>
    </div>
    <el-card style="margin-top: 12px">
      <div>
        <el-button type="primary" @click="handleAdd(2)">提交</el-button>
        <el-button @click="handleAdd(1)">保存草稿</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import { uploadAttachmentApi } from "@/api/modules/common.api";
import {
  getHonorRollDetailApi,
  updateHonorRollListApi,
} from "@/api/modules/honor.api";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";

export default {
  data() {
    return {
      visible: false,
      active: 0,
      moduleList: [],
      add: true,
      html: "",
      limit: 1,
      previewsObj: {},
      outChainFlag: false,
      form: {
        name: "",
        viceTitle: "",
        attrIdList: [],
        content: "",
        id: "",
        status: "",
      },
      editorOptions: {
        placeholder: "",
      },
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      uploadApi: uploadAttachmentApi,
      fileData: {
        objType: 1,
      },
      filePicData: {
        objType: 5,
      },
      fileList: [],
      filePicList: [],
      showFileList: [],
      showFilePicList: [],
      editor: null,
      defaultContent: [
        {
          type: "paragraph",
          lineHeight: "1.5",
          children: [{ text: "", fontFamily: "仿宋", fontSize: "22px" }],
        },
      ],
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          //配置上传图片
          uploadImage: {
            // 自定义上传图片 方法
            // customUpload: this.uploadImg,
            // 自定义插入图片 方法
            // customInsert: this.insertImg,
            //server必须要配置正确,我这里因为上传图片有点特殊，在下面方法配置了，所以此处不用配置地址
            server: uploadAttachmentApi,
            // maxFileSize: 4 * 1024 * 1024, // 1M
            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 100,
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            // allowedFileTypes: [],
            // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
            fieldName: "file",
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
            meta: {
              objType: 2,
              bizId: this.$route.query.id,
            },
            // 将 meta 拼接到 url 参数中，默认 false
            metaWithUrl: false,
            // 跨域是否传递 cookie ，默认为 false
            withCredentials: false,
            // 超时时间，默认为 10 秒
            timeout: 5 * 1000, // 5 秒

            // 单个文件上传失败
            onFailed(file, res, error) {
              // TS 语法
              // onFailed(file, res) {           // JS 语法
              console.log(`${file.name} 上传失败`, res);
              console.log("error", error);
            },

            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
              // TS 语法
              // onError(file, err, res) {               // JS 语法
              console.log(`${file.name} 上传出错`, err, res);
            },

            // customUploadImg(files, insert) {
            //   console.log('files', files)
            //   console.log('insert', insert)
            // }
          },
          // 配置上传视频（同上传图片）
          // uploadVideo: {},
        },
      },
    };
  },
  components: {
    Editor,
    Toolbar,
    // quillEditor,
  },
  mounted() {
    this.getDetail(this.$route.query.id);
    this.form.id = this.$route.query.id;
    // this.editorConfig.MENU_CONF.meta.bizId=this.form.id;
    // this.editorConfig.MENU_CONF.meta.bizId=this.form.id;
  },
  methods: {
    ...mapMutations("base", ["setBreadcrumb"]),
    async getDetail(id) {
      if (id) {
        const res = await getHonorRollDetailApi(id);
        // console.log(res);
        this.form.name = res.name;
        // this.form.viceTitle = res.viceTitle;
        this.html = res.content;
        res.attachmentList.forEach((item) => {
          this.showFilePicList.push({
            name: item.fileName,
            url: item.filePath,
            id: item.attachmentId,
            attrType: item.attrType,
          });
          this.filePicList.push(item.attachmentId);
        });
        this.loading = false;
      }
    },
    async handleAdd(status) {
      this.form.attrIdList = this.filePicList;
      this.form.status = status;
      await updateHonorRollListApi(this.form);
      this.$message({
        message: "成功",
        type: "success",
      });
      await this.$router.push({ path: "/writings/honor" });
      this.setBreadcrumb([
        {
          name: "文章管理",
          path: "/writings",
        },
        {
          name: "光荣榜",
          path: "/honor/list",
        },
      ]);
    },
    onChange(editor) {
      this.form.content = editor.getHtml();
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
    },
    handleBack() {
      this.add = true;
    },
    handleOutChainFlag(value) {
      this.outChainFlag = value;
    },
    handleRemove(file, fileList) {
      this.fileList = [];
      fileList.forEach((item) => {
        if (item.response.code === 200) {
          this.fileList.push(item.response.data.attachmentId);
        }
      });
    },
    handleUpload(response, f, fileList) {
      this.fileList = [];
      fileList.forEach((item) => {
        if (item.response.code === 200) {
          this.fileList.push(item.response.data.attachmentId);
        }
      });
    },
    handleUploadPic(response, f, fileList) {
      this.filePicList = [];
      fileList.forEach((item) => {
        if (item.response.code === 200) {
          this.filePicList.push(item.response.data.attachmentId);
        }
      });
    },
    handleRemovePic(file, fileList) {
      this.filePicList = [];
      fileList.forEach((item) => {
        if (item.response.code === 200) {
          this.filePicList.push(item.response.data.attachmentId);
        }
      });
    },
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy();
  },
};
</script>
<style scoped>
.box {
  height: calc(100vh - 60px - 50px - 48px);
  overflow: auto;
}

.editor-box {
  height: calc(100vh - 60px - 50px - 48px - 200px);
  overflow-y: hidden;
}
</style>
